import { FILE_SIZE } from '../constants';

/**
 * 格式化字节大小为可读形式
 */
export function formatBytes(bytes: number, decimals: number = 2): string {
  if (!bytes || bytes === 0) return '0 B';
  if (bytes < 0) return '0 B';

  const k = FILE_SIZE.KB;
  const dm = Math.max(0, decimals);
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const sizeIndex = Math.min(i, sizes.length - 1);

  return parseFloat((bytes / Math.pow(k, sizeIndex)).toFixed(dm)) + ' ' + sizes[sizeIndex];
}

/**
 * 格式化日期时间为可读形式
 */
export function formatDateTime(dateStr: string | undefined | null): string {
  if (!dateStr) {
    return '未知时间';
  }
  
  try {
    // 处理Java LocalDateTime格式 (例如: 2023-12-01T10:30:00)
    let date: Date;
    
    if (dateStr.includes('T')) {
      // 如果是ISO格式或LocalDateTime格式
      if (dateStr.includes('Z') || dateStr.includes('+')) {
        // 已经包含时区信息
        date = new Date(dateStr);
      } else {
        // LocalDateTime格式，假设为本地时间
        date = new Date(dateStr);
    }
    } else {
      // 其他格式
      date = new Date(dateStr);
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.error('Invalid date string:', dateStr);
      return '无效时间';
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('Error formatting date:', dateStr, error);
    return '格式错误';
  }
}

/**
 * 格式化分享率为字符串
 */
export function formatShareRatioSimple(ratio: number): string {
  return ratio.toFixed(2);
}

/**
 * 格式化分享率为带颜色的状态
 */
export function formatShareRatio(ratio: number): { text: string; color: string } {
  if (ratio < 0.5) {
    return { text: '危险', color: '#f5222d' };
  } else if (ratio < 1.0) {
    return { text: '警告', color: '#faad14' };
  } else if (ratio < 2.0) {
    return { text: '良好', color: '#52c41a' };
  } else {
    return { text: '优秀', color: '#1890ff' };
  }
}

/**
 * 格式化相对时间
 */
export function formatRelativeTime(dateStr: string | number | Date): string {
  try {
    const date = new Date(dateStr);

    if (isNaN(date.getTime())) {
      return '时间无效';
    }

    const now = new Date();
    const diff = now.getTime() - date.getTime();

    // 如果是未来时间
    if (diff < 0) {
      return formatDateTime(date.toISOString());
    }

    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const weeks = Math.floor(days / 7);
    const months = Math.floor(days / 30);
    const years = Math.floor(days / 365);

    if (years > 0) {
      return `${years}年前`;
    } else if (months > 0) {
      return `${months}个月前`;
    } else if (weeks > 0) {
      return `${weeks}周前`;
    } else if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else if (seconds > 30) {
      return `${seconds}秒前`;
    } else {
      return '刚刚';
    }
  } catch (error) {
    console.error('Error formatting relative time:', dateStr, error);
    return '时间错误';
  }
}

// 为了向后兼容，保留 formatSize 作为 formatBytes 的别名
export const formatSize = formatBytes;